<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/10
 * Time: 16:40
 */

namespace Admin\Controller;
use Admin\Controller\AdminController;
use Admin\Model\ConsultingModel;
use Admin\Model\ReplyModel;
use Admin\Model\NewsCateModel;
use Common\Lib\Util\LogUtil;

/**
 * @todo 用户咨询模块
 * @menu 用户咨询管理
 * @author yaoyuanhua
 * @menuAuto index
 * @order 250
 * @icon org.png
 */
class ConsultingController extends AdminController
{
    private $consulting;
    private $newsCate;
    private $reply;
    private $user;
    function __construct() {
        parent::__construct();
        $this->consulting = D('Consulting');
        $this->reply = D('Reply');
        $this->newsCate = new NewsCateModel();
        $this->user = M('users');

    }

    /**
     * @todo 咨询列表
     * @menu 咨询列表
     * @order 1
     */
    public function index() {
        $consulList = $this->getConsultData();
        $cateList = $this->newsCate->getList();
        $this->assign("consulList",$consulList);
        $this->assign("cateList", $cateList);
        $this->display();
    }

    /**
     * @todo 回复
     */
    public function reply() {
        $id = I('id');
        $reply = $this->reply->where(array('consult_id'=>$id))->order('reply_time ASC')->select();
        $consult = $this->consulting->where(array('id'=>$id))->find();
        $this->assign("reply",$reply);
        $this->assign("consult",$consult);
        $this->assign("id",$id);
        $this->display();
    }

    /**
     * @todo 回复操作
     */
    public function doReply()
    {
        if ($data = $this->consulting->create()) {
            $data['reply_time'] = time();
            $data['reply_id'] = $_SESSION['userId'];
            $rs = $this->reply->add($data);
            if ($rs !== false) {
                $this->consulting->where(array('id' => $_POST['consult_id']))->save(array('status' => 2));//修改咨询处理状态
                $res = $this->reply->relation('consult')->where(array('id' => $rs))->find();
                $this->sendReplyNotice($res);
                $this->ajaxReturn(array("status" => true, 'msg' => '咨询回复成功'));
            } else {
                $this->ajaxReturn(array("status" => true, 'msg' => '咨询回复失败'));
            }

        }
    }
    /**
     * @todo 删除
     */
    public function delConsult(){
        $id = I('id');
        $data = array('is_delete'=>1);
        $this->consulting->delConsultById($id,$data);
        $this->ajaxReturn(true);
    }

    private function exportExcel($expTitle,$expCellName,$expTableData){
        vendor("PHPExcel.PHPExcel");
        vendor("PHPExcel.PHPExcel.IOFactory");

        $objPHPExcel = new \PHPExcel();
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
        $xlsTitle = iconv('utf-8', 'gb2312', '咨询');//文件名称
        $fileName = "咨询查询导出.xls";
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1','咨询数据')->getStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);


        for($i=0;$i<$cellNum;$i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]);
        }
        // Miscellaneous glyphs, UTF-8
        for($i=0;$i<$dataNum;$i++){
            for($j=0;$j<$cellNum;$j++){
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
            }
        }

        //header('pragma:public');

        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output'); // 文件通过浏览器下载
        exit;
    }
    /**
     *
     * @todo 导出
     */
    public function load(){
        $xlsName  = "";
        $xlsCell  = array(
            array('id','序号'),
            array('title','标题'),
            array('consult_id','咨询者'),
            array('content','咨询内容'),
            array('consult_time','咨询时间')

        );

        $xlsData = $this->getConsultData(true);
        foreach ($xlsData['list'] as $k => $v)
        {
            $xlsData['list'][$k]['id']=$k+1;
            $xlsData['list'][$k]['consult_id']=getUserName($v['consult_id']);
            $xlsData['list'][$k]['consult_time']=date('Y-y-d H:i:s',$v['consult_id']);
        }

        $this->exportExcel($xlsName,$xlsCell,$xlsData['list']);

    }

    private function getConsultData($export){
        $this->setForm();
        $where['is_delete'] = 0;
        if(IS_POST){
            $cate_id = I('cate_id');
            if(!empty($cate_id)){
                $where['cate_id'] = array('in',$this->newsCate->getChild($cate_id));
            }
            $title = I('title');
            if(!empty($title)){
                $where['title'] = array('like',"%".$title."%");
            }
        }
        if($export == true){
            return  $this->consulting->getConsultingList($where);

        }else{
            return  $this->consulting->getConsultingList($where,$size=15);//咨询数据列表
        }
    }
    //发送咨询回复通知
    private function sendReplyNotice($res) {
        vendor('WeiXinSDK.wechat','','.class.php');
        $options = array(
            'appid' => C('appId'),
            'appsecret' => C('appSecret')
        );
        $weObj = new \Wechat($options);
        $touser = $this->user->where(array('id'=>$res['consult']['consult_id']))->getField('openid');
        $data = array(
            //接收者openid
            'touser' => $touser,
            //模板ID
            'template_id' => C('WEIXIN_TEMPLATE_CONSULT_REPLY'),
            //模板跳转链接，不填则不用跳转
            'url' => SERVER_NAME.U('WeiXin/Consult/detail',array('id'=>$res['consult_id'])),
            //模板数据
            'data' => array(
                'first'=> array('value' => '你的咨询已得到反馈','color' => '#173177'),
                //咨询内容
                'keyword1' => array('value' => sprintf('%s',$res['consult']['content']),'color' => '#173177'),
                //回复事项
                'keyword2' => array('value' => sprintf('%s',$res['content']),'color' => '#173177'),
                //回复时间
                'keyword3' => array('value' => sprintf('%s',date('Y-m-d H:i:s',$res['reply_time'])),'color' => '#173177'),
                //备注
                'remark' => array('value' => '感谢你的参与。','color' => '#173177')
            )
        );
        $result = $weObj->sendTemplateMessage($data);
        $userType = '普通用户';
        LogUtil::info(sprintf('发送回复通知！接收方用户类型：%s',$userType));
        if (is_array($result)) {
            $result['replyId'] = $res['id'];
            $result['toUser'] = $touser;
            $result['userType'] = $userType;
            LogUtil::info($result);
        } else {
            LogUtil::info(sprintf('回复id : %s , openId : %s , 用户类型 : %s , 信息 : %s', $res['id'], $touser, $userType, $weObj->errMsg));
        }
        return $result;
    }

        /**
         * @todo 关闭回复
         */
        public function cloConsult(){
            $id = I('consultId');
            $data = array(
                'status'=>3
            );
            $rs = $this->consulting->where("id = ".$id)->save($data);
           if($rs !==false){
               $this->ajaxReturn(true);
           }

        }

        /**
         * @todo 启用回复
         */
        public function opConsult(){
            $id = I('consultId');
            $data = array(
                'status'=>2
            );
            $rs = $this->consulting->where("id = ".$id)->save($data);
           if($rs !== false){
               $this->ajaxReturn(true);
           }

        }
}